package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 营业额统计
 */
@Service
public class ReportServiceImpl implements ReportService {
  @Autowired
  private ReportMapper reportMapper;
  @Autowired
  private WorkspaceService workspaceService;

  @Override
  public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
    // 1. 计算datalist
    List<LocalDate> dateList = new ArrayList<>();
    dateList.add(begin);
    while (!begin.isEqual(end)){
      begin = begin.plusDays(1); // 加1天
      dateList.add(begin);
    }
    String dataListStr = StringUtils.join(dateList, ","); // 把日期类型的数组转为字符串，以逗号分割

    // 2. 查询每天的营业额
    List<Double> turnoverList = new ArrayList<>();
    for (LocalDate localDate : dateList) {
      // 查询每个日期对应的营业额
      // 营业额：状态为已完成的订单金额合计
      LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
      LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
      Map map = new HashMap();
      map.put("beginTime",beginTime);
      map.put("endTime",endTime);
      map.put("status", Orders.COMPLETED);

      Double turnover = reportMapper.getTurnoverByDay(map);
      turnover = turnover == null ? 0.0 : turnover; // 如果当前营业额没有，查出来的是null，需要转成0.0
      turnoverList.add(turnover);

    }
    String turnoverListStr = StringUtils.join(turnoverList, ",");
    return TurnoverReportVO.builder()
      .dateList(dataListStr)
      .turnoverList(turnoverListStr)
      .build();
  }

  /**
   * 用户统计
   * @param begin
   * @param end
   * @return
   */
  @Override
  public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
    // 1. 获取dateList => 每一天的
    List<LocalDate> dateList = new ArrayList<>();
    dateList.add(begin);
    while(!begin.isEqual(end)){
      begin = begin.plusDays(1);
      dateList.add(begin);
    }
    String dateListStr = StringUtils.join(dateList, ",");

    // 2. 查询每天的新增用户数以及用户总量
    List<Long> userNumList = new ArrayList<>(); // 每天新增用户量
    List<Long> totalUserList = new ArrayList<>(); // 每天总用户量
    for (LocalDate date : dateList) {
      LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
      LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);
      Map map = new HashMap();
      map.put("endTime",endTime);

      // 查询每天的总用户量
      Long userCount = reportMapper.getUserCount(map);
      userCount = userCount == null ? 0 : userCount;
      totalUserList.add(userCount);

      // 查询每天新增的用户数量
      map.put("beginTime",beginTime);
      Long userCountByDay = reportMapper.getUserCount(map);
      userCountByDay = userCountByDay == null ? 0 : userCountByDay;
      userNumList.add(userCountByDay);
    }
    String userCountByDayStr = StringUtils.join(userNumList, ",");
    String totalUserListStr = StringUtils.join(totalUserList,",");
    return UserReportVO.builder()
      .dateList(dateListStr)
      .newUserList(userCountByDayStr)
      .totalUserList(totalUserListStr)
      .build();
  }

  /**
   * 订单统计
   * dateList：日期列表
   * orderCompletionRate：订单完成率（有效订单数 / 订单总数 * 100%）
   * orderCountList：订单数列表
   * totalOrderCount： 订单总数
   * validOrderCount：有效订单数（状态为已完成的订单）
   * validOrderCountList：有效订单数列表
   * @param begin
   * @param end
   * @return
   */
  @Override
  public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
    List<LocalDate> dateList = new ArrayList<>();
    dateList.add(begin);
    while(!begin.isEqual(end)){
      begin = begin.plusDays(1);
      dateList.add(begin);
    }
    String dateListStr = StringUtils.join(dateList,",");

    List<Integer> orderCountList = new ArrayList<>();
    List<Integer> validOrderCountList = new ArrayList<>();
    Integer totalOrderCount = 0;
    Integer validOrderCount = 0;
    for (LocalDate date : dateList) {
      LocalDateTime beginTime = LocalDateTime.of(date,LocalTime.MIN);
      LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);
      Map map = new HashMap();
      map.put("beginTime",beginTime);
      map.put("endTime",endTime);
      Integer orderList = reportMapper.getOrder(map);
      orderCountList.add(orderList);

      map.put("status",Orders.COMPLETED);
      Integer validOrderList = reportMapper.getOrder(map);
      validOrderCountList.add(validOrderList);
    }
    Map map = new HashMap();
    map.put("beginTime",LocalDateTime.of(dateList.get(0),LocalTime.MIN));
    map.put("endTime",LocalDateTime.of(dateList.get(dateList.size()-1),LocalTime.MAX));
    totalOrderCount = reportMapper.getOrderCount(map);
    map.put("status",Orders.COMPLETED);
    validOrderCount = reportMapper.getOrderCount(map);

    String orderCountListStr = StringUtils.join(orderCountList,",");
    String validOrderCountListStr = StringUtils.join(validOrderCountList,",");

    Double orderCompletionRate = (double)validOrderCount / totalOrderCount;
    return OrderReportVO.builder()
      .dateList(dateListStr)
      .orderCountList(orderCountListStr)
      .validOrderCountList(validOrderCountListStr)
      .totalOrderCount(totalOrderCount)
      .validOrderCount(validOrderCount)
      .orderCompletionRate(orderCompletionRate)
      .build();
  }

  /**
   * 获取销售额统计前10
   * nameList: 商品名称列表，以逗号分隔
   * numberList: 销量列表，以逗号分隔
   * @param begin
   * @param end
   * @return
   */
  @Override
  public SalesTop10ReportVO getSalesTop10Statistics(LocalDate begin, LocalDate end) {
    LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);
    LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);
    /**
     * 根据name进行分组：group by od.name
     * 根据销量来排序：order by sum(o.number) desc
     * 取10条：limit 10
     * select od.name,sum(od.number) from order_detail od,orders o where od.order_id=o.id and
     * o.order_time > '2022-01-01 00:00:00' and o.order_time < '2022-01-31 23:59:59' and o.status = 5
     * group by od.name order by sum(od.number) desc limit 10;
     */
    List<GoodsSalesDTO> list = reportMapper.getSalesTop(beginTime,endTime);

    List<String> names = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
    String nameList = StringUtils.join(names,",");

    List<Integer> numbers = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
    String numberList = StringUtils.join(numbers,",");
    /*list.forEach(goodsSalesDTO -> {
      nameList.add(goodsSalesDTO.getName());
      numberList.add(goodsSalesDTO.getNumber().toString());
    });*/
    return SalesTop10ReportVO.builder()
      .nameList(StringUtils.join(nameList,","))
      .numberList(StringUtils.join(numberList,","))
      .build();
  }

  /**
   * 导出运营数据报表
   * @param response
   */
  @Override
  public void exportBusinessData(HttpServletResponse response) {
    // 1. 查询数据库获取运营数据(最近30天)
    LocalDate begin = LocalDate.now().minusDays(30);
    LocalDate end = LocalDate.now().minusDays(1);
    LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
    LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);
    BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);
    // 2. 通过POI将运营数据写入到Excel中
    InputStream template = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

    try {
      XSSFWorkbook excel = new XSSFWorkbook(template); // 读取Excel模板
      // 填充数据
      XSSFSheet sheet1 = excel.getSheet("sheet1");
      sheet1.getRow(1).getCell(1).setCellValue("时间："+begin+" 至 "+end); // 填充时间段
      XSSFRow row = sheet1.getRow(3);
      row.getCell(2).setCellValue(businessData.getTurnover());
      row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
      row.getCell(6).setCellValue(businessData.getNewUsers());

      row = sheet1.getRow(4);
      row.getCell(2).setCellValue(businessData.getValidOrderCount());
      row.getCell(4).setCellValue(businessData.getUnitPrice());

      // 填充明细数据（30天的）
      for (int i = 0; i < 30; i++) {
        LocalDate date = begin.plusDays(i);
        // 查询某一天的营业数据
        BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
        row = sheet1.getRow(i+7);
        row.getCell(1).setCellValue(date.toString());
        row.getCell(2).setCellValue(data.getTurnover());
        row.getCell(3).setCellValue(data.getValidOrderCount());
        row.getCell(4).setCellValue(data.getOrderCompletionRate());
        row.getCell(5).setCellValue(data.getUnitPrice());
        row.getCell(6).setCellValue(data.getNewUsers());
      }

      // 3. 通过输出流将Excel下载到客户端浏览器
      ServletOutputStream out = response.getOutputStream();
      excel.write(out);

      // 4. 关闭资源
      out.close();
      excel.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

  }
}
